package com.geralt.im.commandparse.impl;

import geralt.im.constant.Constant;
import geralt.im.watcher.Observer;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.geralt.im.command.Command;
import com.geralt.im.commandenum.Code;
import com.geralt.im.commandparse.IParser;
import com.geralt.im.commands.impl.BadRequestCommand;
import com.geralt.im.entrance.Entrance;
import com.geralt.im.protocol.Response;

public class RpParser implements IParser {

	private static RpParser rpParser;

	private RpParser() {}

	public static RpParser getInstance() {
		if (rpParser == null) {
			rpParser = new RpParser();
		}
		return rpParser;
	}

	public static final Map<String, Command> keyCommandMap = new HashMap<String, Command>();
	
	static {
		try {
			Properties commandCodeProperties = new Properties();
			Properties responseTypeProperties = new Properties();
			commandCodeProperties.load(new FileInputStream(new File(Constant.COMMAND_CODE_FILE)));
			responseTypeProperties.load(new FileInputStream(new File(Constant.RESPONSE_TYPE_FILE)));
			Set<Object> commandCodeSet = commandCodeProperties.keySet();
			Set<Object> responseTypeSet = responseTypeProperties.keySet();
//			System.out.println("response Type Set"+responseTypeSet);
			for(Object type:responseTypeSet){
				String typeString = (String)type;
				String className = responseTypeProperties.getProperty(typeString);
				String commandCodeString = commandCodeProperties.getProperty(className);
				Command command = (Command) Class.forName(Constant.COMMAND_PACK_NAME+className).getConstructor().newInstance();
//				System.out.println(Integer.parseInt(commandCodeString)+"----------"+command.toString());
				Method setCodeMethod = Class.forName(Constant.COMMAND_PACK_NAME+className).getMethod("setCode", int.class);
				setCodeMethod.invoke(command, Integer.parseInt(commandCodeString));
				keyCommandMap.put(typeString, command);

//				System.out.println(Integer.parseInt(commandCodeString)+"----------"+command.toString());
//				System.out.println(keyCommandMap.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Command parse(Response response) {
//		System.out.println("Code.BAD_REQUEST   "+ Code.BAD_REQUEST+"    "+response.getStatusCode());
//		System.out.println(Code.BAD_REQUEST != response.getStatusCode());
		if (Code.BAD_REQUEST != response.getStatusCode()) {
			Command newCommand = keyCommandMap.get(response.getType());
			System.out.println("deal with command"+newCommand.toString());
			newCommand.setParameter(response.getParameter());
			return newCommand;
		} else {
			System.out.println("BAD_REQUEST");
			Command newCommand = keyCommandMap.get("BAD_REQUEST");
			newCommand.setParameter(response.getParameter());
//			System.out.println("new Command "+newCommand.getParameter());
			return newCommand;
		}
	}

}
